<template>
  <div class="gelly-ai-page">
    <div class="ai-container">
      <!-- App Header -->
      <div class="app-header">
        <div class="back-btn" @click="$router.push('/real/manage')">
          <i class="el-icon-arrow-left"></i>
        </div>
        <div class="ai-logo">
          <img :src="aiLogo" alt="AI Logo" class="header-logo-img" />
        </div>
        <h1 class="ai-title">Gelly 智能核心</h1>
      </div>

      <!-- Chat History -->
      <div ref="chatHistory" class="chat-history">
        <div
          v-for="(message, index) in messages"
          :key="index"
          class="message-row"
          :class="message.role === 'user' ? 'user' : 'ai'"
        >
          <div class="avatar-container" :class="message.role === 'user' ? 'avatar-user' : 'avatar-ai'">
            <img v-if="message.role === 'user'" :src="personMascot" class="avatar-img" />
            <img v-else :src="aiMascot" class="avatar-img" />
          </div>

          <div class="message-content" v-if="message.role === 'user'">
            <div class="message-text" v-html="formatMessage(message.content)"></div>
            <div class="message-details">
              <div class="sender-name">You</div>
            </div>
          </div>

          <div class="message-bubble-wrapper" v-if="message.role === 'assistant'">
            <div class="thinking-process-container" v-if="message.thinking_process">
              <el-collapse v-if="message.isThinkingComplete" class="thinking-collapse" accordion>
                <el-collapse-item name="1">
                  <template slot="title">
                    <i class="el-icon-magic-stick header-icon"></i>&nbsp;已完成思考
                  </template>
                  <div class="thinking-content" v-html="formatMessage(message.thinking_process)"></div>
                </el-collapse-item>
              </el-collapse>
              <div v-else class="thinking-panel">
                <div class="thinking-header">
                  <i class="el-icon-loading"></i>&nbsp;思考中...
                </div>
                <div class="thinking-content" v-html="formatMessage(message.thinking_process)"></div>
              </div>
            </div>
            <div class="message-content" v-if="message.content">
              <div class="message-text" v-html="formatMessage(message.content)"></div>
              <div class="message-details" v-if="!isTyping">
                <div class="sender-name">Gelly AI</div>
                <div class="message-tools">
                  <div class="tool-btn" @click="handleMessageAction('copy', message)">
                    <i class="el-icon-document-copy"></i> Copy
                  </div>
                  <div class="tool-btn" @click="handleMessageAction('work', message)">
                      <i class="el-icon-tickets"></i> 工单
                 </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- Loading Indicator -->
        <div v-if="isTyping && !messages[messages.length-1].content && !messages[messages.length-1].thinking_process" class="message-row ai">
          <div class="avatar-container avatar-ai">
            <img :src="aiMascot" class="avatar-img" />
          </div>
          <div class="loading-indicator">
            <div class="loading-dot"></div>
            <div class="loading-dot"></div>
            <div class="loading-dot"></div>
          </div>
        </div>
      </div>

      <!-- Suggestions -->
      <div class="suggestions-container">
        <div
          v-for="(question, index) in suggestedQuestions"
          :key="index"
          class="suggestion-card"
          @click="askSuggestedQuestion(question.text)"
        >
          <div class="suggestion-title">{{ question.title }}</div>
          <div class="suggestion-text">{{ question.text }}</div>
        </div>
      </div>

      <!-- Input Area -->
      <div class="input-container">
        <div class="input-box">
          <textarea
            ref="messageInput"
            class="message-input"
            v-model="userInput"
            placeholder="Ask Gelly anything..."
            rows="1"
            :disabled="isTyping"
            @keydown="handleKeyDown"
            @input="resizeTextarea"
          ></textarea>
          <div class="input-controls">
            <!-- 魔法棒按钮 -->
            <button class="ai-btn" @click="handleMagicWandClick" :disabled="!sensorDataForAI || isGeneratingByAI">
              <span :class="{ 'magic-wand-spin': isGeneratingByAI }">
              <svg width="28" height="28" viewBox="0 0 28 28" fill="none" xmlns="http://www.w3.org/2000/svg">
                <g>
                  <rect x="12" y="4" width="4" height="10" rx="2" fill="#7e6cf7"/>
                  <rect x="13.5" y="2" width="1" height="4" rx="0.5" fill="#f7d51d"/>
                  <rect x="13.5" y="22" width="1" height="4" rx="0.5" fill="#f7d51d"/>
                  <rect x="2" y="13.5" width="4" height="1" rx="0.5" fill="#f7d51d"/>
                  <rect x="22" y="13.5" width="4" height="1" rx="0.5" fill="#f7d51d"/>
                  <rect x="6.22" y="6.22" width="2" height="6" rx="1" transform="rotate(-45 6.22 6.22)" fill="#b4a7f7"/>
                  <rect x="19.78" y="19.78" width="2" height="6" rx="1" transform="rotate(-45 19.78 19.78)" fill="#b4a7f7"/>
                </g>
              </svg>
            </span>
            </button>
            <!-- 发送按钮 -->
            <button class="send-btn" @click="sendMessage" :disabled="!userInput.trim() || isTyping">
              <svg width="22" height="22" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M5.30907 11.9474C5.01618 11.8315 4.99686 11.4393 5.27661 11.2965L20.037 3.35718C20.3302 3.20653 20.6417 3.492 20.5311 3.78687L15.67 17.1869C15.5736 17.4439 15.246 17.5133 15.0576 17.3259L12 14.2683" stroke="white" stroke-width="2" stroke-linecap="round"></path>
                <path d="M11.4268 14.3095L8.02117 17.7151C7.7347 18.0015 7.7347 18.4712 8.02117 18.7577V18.7577C8.30764 19.0441 8.77734 19.0441 9.06381 18.7577L12.4694 15.352" stroke="white" stroke-width="2" stroke-linecap="round"></path>
              </svg>
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex';
import aiMascot from '@/assets/images/ai_mascot.png';
import personMascot from '@/assets/images/person_mascot.png';
import aiLogo from '@/assets/images/ai_logo.png';
import { marked } from 'marked';
import DOMPurify from 'dompurify';
import request from '@/utils/request';
import { getWaveformDataByrangeTime } from '@/api/real/waveform';
import { getAccelerationData, getDetectInfo } from '@/api/real/detect';

export default {
  name: 'InquiryChat',
  data() {
    return {
      userInput: '',
      suggestedQuestions: [
        { title: '故障诊断', text: '主轴震动异常如何解决？' },
        { title: '参数优化', text: '如何优化切削参数？' },
        { title: '周期维护', text: '设备维护的最佳周期是多久？' },
      ],
      aiMascot,
      personMascot,
      aiLogo,
      isGeneratingByAI: false, // 新增：控制AI描述生成时的加载状态
      sensorDataForAI: null, // 新增：存储页面加载时获取的传感器数据
    };
  },
  computed: {
    ...mapState('chat', ['messages', 'isTyping'])
  },
  watch: {
    messages: {
      handler() {
        this.scrollToBottom();
      },
      deep: true
    }
  },
  created() {
    const { sensorId, latheName, axis, desc } = this.$route.query || {};

    if (sensorId) {
      const endTime = new Date();
      const startTime = new Date(endTime.getTime() - 10 * 60 * 1000);

      const formatDateTime = (date) => {
          const Y = date.getFullYear();
          const M = (date.getMonth() + 1).toString().padStart(2, '0');
          const D = date.getDate().toString().padStart(2, '0');
          const h = date.getHours().toString().padStart(2, '0');
          const m = date.getMinutes().toString().padStart(2, '0');
          const s = date.getSeconds().toString().padStart(2, '0');
          return `${Y}-${M}-${D} ${h}:${m}:${s}`;
      };

      const waveformPromise = getWaveformDataByrangeTime(sensorId, formatDateTime(startTime), formatDateTime(endTime), sensorId);
      const statusPromise = getAccelerationData(sensorId);
      // 新增：调用getDetectInfo获取可能包含温度的详细信息
      const detailPromise = getDetectInfo();

      // 修改为三个并行请求
      Promise.all([waveformPromise, statusPromise, detailPromise])
        .then(([waveformResponse, statusResponse, detailResponse]) => {
          // 详细打印状态API的响应，寻找可能的温度数据
          console.log('--- Raw response from getAccelerationData ---', statusResponse);
          console.log('--- Raw response from getDetectInfo ---', detailResponse);

          // 检查detailResponse中是否有温度相关数据
          if (detailResponse && detailResponse.data) {
            console.log('--- Detail data fields ---', Object.keys(detailResponse.data));
            // 如果detailResponse.data是数组，尝试找到与当前sensorId匹配的项
            if (Array.isArray(detailResponse.data)) {
              const sidNum = Number(sensorId);
              const matchingDevice = detailResponse.data.find(item =>
                Number(item.deviceId) === sidNum || Number(item.dataId) === sidNum
              );
              if (matchingDevice) {
                console.log('--- Matching device in detailResponse ---', matchingDevice);
              }
            }
          }

          // 检查statusResponse中是否有温度相关数据
          if (statusResponse && statusResponse.data) {
            console.log('--- Status data fields ---', Object.keys(statusResponse.data));
            // 打印所有可能包含"温度"或"temp"的字段
            const possibleTempFields = Object.keys(statusResponse.data).filter(key =>
              key.toLowerCase().includes('temp') ||
              key.toLowerCase().includes('温度') ||
              key.toLowerCase().includes('heat') ||
              key.toLowerCase().includes('degree')
            );
            console.log('--- Possible temperature fields in statusResponse ---', possibleTempFields);
            if (possibleTempFields.length > 0) {
              possibleTempFields.forEach(field => {
                console.log(`--- Field ${field} value ---`, statusResponse.data[field]);
              });
            }
          }

          // 检查请求是否都成功并返回了有效数据
          const isWaveformValid = waveformResponse && waveformResponse.data && waveformResponse.data.length > 0;
          const isStatusValid = statusResponse && statusResponse.code === 200 && statusResponse.data;
          const isDetailValid = detailResponse && detailResponse.code === 200 && detailResponse.data;

          if (isWaveformValid && (isStatusValid || isDetailValid)) {
            const waveformData = waveformResponse.data[0];
            const statusData = statusResponse.data || {};
            const detailData = detailResponse.data || {};
            const extraData = waveformData.extraData || {};

            let temperature = 0.0;
            let candidate;
            if (isDetailValid) {
              const sidNum = Number(sensorId);
              candidate = Array.isArray(detailData)
                ? detailData.find(item => Number(item.deviceId) === sidNum || Number(item.dataId) === sidNum)
                : detailData;
              temperature = this.findTemperature(candidate) ?? temperature;
            }
            if (temperature === 0.0 && isStatusValid) {
              temperature = this.findTemperature(statusData) ?? temperature;
            }
            if (temperature === 0.0) {
              temperature = this.findTemperature(waveformData) ?? temperature;
            }
            if (temperature === 0.0) temperature = 40.0;

            this.sensorDataForAI = {
              deviceName: latheName,
              sensorId: sensorId,
              deviceId: sensorId,
              position: axis || waveformData.location || '',
              // 使用找到的或模拟的温度
              temperature: temperature,
              rmsX: extraData.xRmsData || [],
              rmsY: extraData.yRmsData || [],
              rmsZ: extraData.zRmsData || [],
              peakX: extraData.xPeakData || [],
              peakY: extraData.yPeakData || [],
              peakZ: extraData.zPeakData || [],
            };
            console.log('--- Sensor data prepared and ready for AI ---', this.sensorDataForAI);

            // 数据准备完成后，立即开始静默生成AI描述
            setTimeout(() => {
              this.silentGenerateDescription();
            }, 500);
          } else {
            console.error(`Data pre-fetch failed. Waveform valid: ${isWaveformValid}, Status valid: ${isStatusValid}, Detail valid: ${isDetailValid}`);
          }
        })
        .catch((error) => {
          console.error('--- Error in pre-fetching sensor data ---', error);
        });
    } else {
      // 如果缺少关键ID，直接使用旧的拼接逻辑
      const parts = [];
      if (latheName) parts.push(`设备 ${latheName}`);
      if (sensorId) parts.push(`传感器编号 ${sensorId}`);
      if (axis) parts.push(`监测轴 ${axis}`);
      const base = parts.join('，');
      this.userInput = desc
        ? `${base} 出现异常：${desc}，请给出诊断建议。`
        : `请帮我分析 ${base} 的异常原因。`;
    }
  },
  mounted() {
    this.scrollToBottom();
    this.resizeTextarea();

    // 添加页面可见性监听，确保AI输出不会因为切换标签页而中断
    this.setupVisibilityHandling();
  },
  beforeDestroy() {
    // 清理事件监听器
    document.removeEventListener('visibilitychange', this.handleVisibilityChange);
    window.removeEventListener('blur', this.handleWindowBlur);
    window.removeEventListener('focus', this.handleWindowFocus);
  },
  methods: {
    ...mapActions('chat', {
      sendMessageAction: 'sendMessage',
    }),
    // Helper: find temperature from arbitrary object keys
    findTemperature(obj) {
      if (!obj || typeof obj !== 'object') return null;
      for (const [key, val] of Object.entries(obj)) {
        if (typeof val === 'number' && /temp|温度|temperature|heat|degree/i.test(key)) {
          return val;
        }
      }
      return null;
    },

    // 清理AI输出文本，移除无意义的结尾套话
    cleanAIOutput(text) {
      if (!text) return text;

      // 定义常见的AI套话模式
      const meaninglessPatterns = [
        // 总结性套话
        /通过以上分析.*?确保.*?。?\s*$/i,
        /以上.*?分析.*?解决方案.*?。?\s*$/i,
        /综上所述.*?。?\s*$/i,
        /总之.*?。?\s*$/i,
        /希望.*?有所帮助.*?。?\s*$/i,
        /如.*?需要.*?技术支持.*?。?\s*$/i,
        /如.*?进一步.*?支持.*?联系.*?。?\s*$/i,
        /以上.*?针对.*?故障分析.*?解决方案.*?。?\s*$/i,

        // 新增：更多总结套话
        /###\s*总结[:：][\s\S]*$/i,
        /建议按照.*?排查思路.*?解决方案.*?。?\s*$/i,
        /.*?的异常类型为.*?故障原因.*?建议.*?。?\s*$/i,

        // 客套话
        /如需.*?帮助.*?随时联系.*?。?\s*$/i,
        /祝.*?工作顺利.*?。?\s*$/i,
        /感谢.*?。?\s*$/i,

        // 重复的分隔符和结尾
        /---+\s*$/,
        /####?\s*$/,
        /\*\*\*+\s*$/,

        // 空的段落标记
        /^\s*---\s*$/m,
        /^\s*####?\s*$/m
      ];

      let cleanedText = text;

      // 逐个应用清理模式
      meaninglessPatterns.forEach(pattern => {
        const beforeClean = cleanedText;
        cleanedText = cleanedText.replace(pattern, '');
        if (beforeClean !== cleanedText) {
          console.log('🧹 移除AI套话:', pattern.source);
        }
      });

      // 清理多余的空行和空格
      cleanedText = cleanedText
        .replace(/\n\s*\n\s*\n/g, '\n\n') // 多个空行合并为两个
        .replace(/\s+$/g, '') // 移除结尾空格
        .trim();

      if (cleanedText !== text) {
        console.log('🧹 AI文本清理完成');
        console.log('原文长度:', text.length, '清理后长度:', cleanedText.length);
      }

      return cleanedText;
    },

    // 格式化当前时间为本地时间字符串
    formatCurrentTime(date = new Date()) {
      // 确保使用本地时间（中国时区）
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');

      const formatted = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      console.log('🕐 问询页面生成时间:', formatted, '原始时间对象:', date);
      return formatted;
    },

    // 通用数字提取函数 - 支持多种AI输出格式
    extractNumberFromText(text, keyword, minValue = 0, maxValue = 99) {
      const patterns = [
        // Markdown格式：### 关键词：\n**数字（描述）**
        new RegExp(`###\\s*${keyword}[:：]\\s*[\\s\\n]*\\*\\*(\\d+)[^0-9]*\\*\\*`, 'i'),
        // Markdown格式：### 关键词：\n数字（描述）
        new RegExp(`###\\s*${keyword}[:：]\\s*[\\s\\n]*(\\d+)`, 'i'),
        // 普通格式：关键词：2=描述
        new RegExp(`${keyword}[:：]\\s*[\\s\\n]*(\\d+)=?[^0-9]*`, 'i'),
        // 普通格式：关键词：2（描述）
        new RegExp(`${keyword}[:：]\\s*[\\s\\n]*(\\d+)\\s*（[^）]*）`, 'i'),
        // 普通格式：关键词：2(描述)
        new RegExp(`${keyword}[:：]\\s*[\\s\\n]*(\\d+)\\s*\\([^)]*\\)`, 'i'),
        // 普通格式：关键词：数字2
        new RegExp(`${keyword}[:：]\\s*[\\s\\n]*数字?(\\d+)`, 'i'),
        // 普通格式：关键词：2
        new RegExp(`${keyword}[:：]\\s*[\\s\\n]*(\\d+)`, 'i'),
        // 加粗格式：**数字（描述）**
        new RegExp(`\\*\\*(\\d+)\\s*（[^）]*${keyword}[^）]*）\\*\\*`, 'i'),
        // 加粗格式：**数字(描述)**
        new RegExp(`\\*\\*(\\d+)\\s*\\([^)]*${keyword}[^)]*\\)\\*\\*`, 'i')
      ];

      for (let i = 0; i < patterns.length; i++) {
        const match = text.match(patterns[i]);
        if (match && match[1]) {
          const num = parseInt(match[1]);
          if (num >= minValue && num <= maxValue) {
            console.log(`✅ 提取${keyword}成功:`, num, `(模式${i + 1}/${patterns.length}): ${patterns[i].source}`);
            return num;
          }
        }
      }

      console.log(`❌ 未能提取${keyword}，尝试了${patterns.length}种模式`);
      // 显示相关文本片段用于调试
      const keywordIndex = text.indexOf(keyword);
      if (keywordIndex !== -1) {
        const snippet = text.substring(keywordIndex, keywordIndex + 200);
        console.log(`🔍 ${keyword}相关文本:`, snippet);
      }
      return null;
    },

    // 新增：从AI回复中提取结构化字段
    extractFieldsFromResponse(text) {
      if (!text) return {};

      console.log('=== 开始提取字段 ===');
      console.log('AI原始回答:', text);

      // 清理AI输出文本
      const cleanedText = this.cleanAIOutput(text);
      console.log('清理后的文本:', cleanedText);

      const fields = {
        anomalyDescription: '',
        faultCause: '',
        solution: '',
        preventiveMeasures: '',
        faultLevel: '',
        anomalyType: '',
        troubleshootingProcess: '',
        similarCases: '',
        impactAssessment: '',
        workSection: '',
        productionPart: '',
        replacedParts: '',
        toolsUsed: '',
        operationSteps: ''
      };

      // 使用清理后的文本进行字段提取
      const textToProcess = cleanedText;

      // 提取异常描述
      const anomalyMatch = textToProcess.match(/异常描述[:：][\s\n]*([\s\S]*?)(?=故障原因[:：]|故障等级[:：]|异常类型[:：]|解决方案[:：]|$)/i);
      if (anomalyMatch && anomalyMatch[1]) {
        fields.anomalyDescription = anomalyMatch[1].trim();
      }

      // 提取故障原因
      const causeMatch = textToProcess.match(/故障原因[:：][\s\n]*([\s\S]*?)(?=解决方案[:：]|故障等级[:：]|异常类型[:：]|$)/i);
      if (causeMatch && causeMatch[1]) {
        fields.faultCause = causeMatch[1].trim();
      }

      // 提取解决方案
      const solutionMatch = textToProcess.match(/解决方案[:：][\s\n]*([\s\S]*?)(?=预防措施[:：]|故障等级[:：]|异常类型[:：]|$)/i);
      if (solutionMatch && solutionMatch[1]) {
        fields.solution = solutionMatch[1].trim();
      }

      // 提取预防措施
      const preventiveMatch = textToProcess.match(/预防措施[:：][\s\n]*([\s\S]*?)(?=故障等级[:：]|异常类型[:：]|$)/i);
      if (preventiveMatch && preventiveMatch[1]) {
        fields.preventiveMeasures = preventiveMatch[1].trim();
      }

      // 提取故障等级 - 使用通用提取函数
      console.log('🔍 开始提取故障等级...');
      const faultLevel = this.extractNumberFromText(textToProcess, '故障等级', 0, 3);
      if (faultLevel !== null) {
        fields.faultLevel = faultLevel.toString();
        console.log('✅ 故障等级提取成功:', faultLevel);
      } else {
        console.log('❌ 故障等级提取失败');
      }

      // 提取异常类型 - 使用通用提取函数
      console.log('🔍 开始提取异常类型...');
      const anomalyType = this.extractNumberFromText(textToProcess, '异常类型', 0, 9);
      if (anomalyType !== null) {
        fields.anomalyType = anomalyType.toString();
        console.log('✅ 异常类型提取成功:', anomalyType);
      } else {
        console.log('❌ 异常类型提取失败');
      }

      // 提取排查思路
      const troubleshootingMatch = textToProcess.match(/排查思路[:：][\s\n]*([\s\S]*?)(?=解决方案[:：]|预防措施[:：]|$)/i);
      if (troubleshootingMatch && troubleshootingMatch[1]) {
        fields.troubleshootingProcess = troubleshootingMatch[1].trim();
      }

      // 提取类似案例
      const similarCasesMatch = textToProcess.match(/类似案例[:：][\s\n]*([\s\S]*?)(?=预防措施[:：]|$)/i);
      if (similarCasesMatch && similarCasesMatch[1]) {
        fields.similarCases = similarCasesMatch[1].trim();
      }

      // 提取影响评估
      const impactMatch = textToProcess.match(/影响评估[:：][\s\n]*([\s\S]*?)(?=解决方案[:：]|预防措施[:：]|$)/i);
      if (impactMatch && impactMatch[1]) {
        fields.impactAssessment = impactMatch[1].trim();
      }

      // 提取受影响轴向 - 增强模式匹配
      const affectedAxes = [];

      // 多种轴向表示方式
      const axisPatterns = [
        { regex: /[XxＸｘ][\s]*轴/g, axis: 'X' },
        { regex: /[YyＹｙ][\s]*轴/g, axis: 'Y' },
        { regex: /[ZzＺｚ][\s]*轴/g, axis: 'Z' }
      ];

      for (const { regex, axis } of axisPatterns) {
        if (regex.test(textToProcess)) {
          affectedAxes.push(axis);
          console.log(`✅ 检测到${axis}轴相关内容`);
        }
      }

      // 去重并排序
      const uniqueAxes = [...new Set(affectedAxes)].sort();

      if (uniqueAxes.length > 0) {
        fields.affectedAxis = uniqueAxes;
        console.log('✅ 从AI输出中提取到受影响轴向:', uniqueAxes);
      } else {
        console.log('❌ 未从AI输出中找到轴向信息');
        // 显示一些可能包含轴向信息的文本片段
        const axisRelatedText = text.match(/[XYZxyz轴振动RMS峰值]{1,20}/g);
        if (axisRelatedText) {
          console.log('🔍 可能相关的文本片段:', axisRelatedText.slice(0, 5));
        }
      }

      console.log('=== 字段提取结果 ===');
      console.log('故障等级:', fields.faultLevel, typeof fields.faultLevel);
      console.log('异常类型:', fields.anomalyType, typeof fields.anomalyType);
      console.log('受影响轴向:', fields.affectedAxis);
      console.log('所有字段:', fields);
      console.log('=== 提取完成 ===');

      // 额外验证
      if (!fields.faultLevel) {
        console.log('⚠️ 故障等级提取失败，检查AI输出格式');
        console.log('AI输出前500字符:', text.substring(0, 500));
      }
      if (!fields.anomalyType) {
        console.log('⚠️ 异常类型提取失败，检查AI输出格式');
        console.log('AI输出前500字符:', text.substring(0, 500));
      }

      return fields;
    },

    // 设置页面可见性处理，确保AI输出不中断
    setupVisibilityHandling() {
      // 监听页面可见性变化
      document.addEventListener('visibilitychange', this.handleVisibilityChange);
      // 监听窗口焦点变化
      window.addEventListener('blur', this.handleWindowBlur);
      window.addEventListener('focus', this.handleWindowFocus);
    },

    handleVisibilityChange() {
      if (document.hidden) {
        console.log('📱 页面切换到后台，AI输出应继续进行');
      } else {
        console.log('📱 页面回到前台');
        // 页面回到前台时，确保滚动到底部显示最新内容
        this.$nextTick(() => {
          this.scrollToBottom();
        });
      }
    },

    handleWindowBlur() {
      console.log('🔍 窗口失去焦点，AI输出应继续进行');
    },

    handleWindowFocus() {
      console.log('🔍 窗口获得焦点');
      // 窗口重新获得焦点时，滚动到底部
      this.$nextTick(() => {
        this.scrollToBottom();
      });
    },

    // 显示内容生成完成的提醒特效
    showContentGeneratedEffect() {
      // 让输入框闪烁一下提示用户内容已生成
      const textarea = this.$refs.messageInput;
      if (textarea) {
        textarea.classList.add('content-generated');
        setTimeout(() => {
          textarea.classList.remove('content-generated');
        }, 2000);
      }

      // 显示提示消息
      this.$message({
        message: '✨ AI已为您生成问题描述，请点击发送按钮进行分析',
        type: 'success',
        duration: 3000
      });
    },

    // 静默生成AI描述（后台进行，用户无感知）
    async silentGenerateDescription() {
      console.log('🔍 检查静默生成条件...');
      console.log('sensorDataForAI:', this.sensorDataForAI);
      console.log('generatedDescription:', this.generatedDescription);

      if (!this.sensorDataForAI) {
        console.log('❌ 没有传感器数据，跳过静默生成');
        return;
      }

      if (this.generatedDescription) {
        console.log('❌ 已经生成过描述，跳过静默生成');
        return;
      }

      try {
        console.log('🔄 后台开始静默生成AI描述...');
        const AUTO_DESC_URL = 'https://api.withoutend.top/api/auto-desc';

        const requestData = {
          sensorData: this.sensorDataForAI,
          structureHint: "请分析数据并生成一个问题描述"
        };

        console.log('📤 发送请求数据:', requestData);
        const res = await request.post(AUTO_DESC_URL, requestData);
        console.log('📥 收到响应:', res);

        if (res && res.description) {
          this.generatedDescription = this.cleanThinkTags(res.description);
          console.log('✅ AI描述静默生成完成，内容长度:', this.generatedDescription.length);
        } else {
          console.log('❌ 响应中没有description字段');
        }
      } catch (error) {
        console.error('❌ 静默生成AI描述失败:', error);
        console.error('错误详情:', error.message);
        console.error('错误堆栈:', error.stack);
      }
    },

    // 魔法棒点击处理（障眼法效果）
    handleMagicWandClick() {
      this.hasClickedMagicWand = true;

      if (this.generatedDescription) {
        // 如果后台已经生成完成，假装生成一下然后显示
        this.fakeGenerationEffect();
      } else {
        // 如果还没生成完，显示真实的生成过程
        this.isGeneratingByAI = true;
        this.waitForSilentGeneration();
      }
    },

    // 假装生成效果（障眼法）
    fakeGenerationEffect() {
      this.isGeneratingByAI = true;

      // 假装生成1-2秒，让用户以为是魔法棒触发的
      const fakeDelay = Math.random() * 1000 + 800; // 800-1800ms随机延迟

      setTimeout(() => {
        this.isGeneratingByAI = false;
        this.userInput = this.generatedDescription;
        this.$nextTick(this.resizeTextarea);
        this.showContentGeneratedEffect();
      }, fakeDelay);
    },

    // 等待静默生成完成
    waitForSilentGeneration() {
      const checkInterval = setInterval(() => {
        if (this.generatedDescription) {
          clearInterval(checkInterval);
          // 找到内容后，再假装生成一小会儿
          const extraDelay = Math.random() * 500 + 300; // 300-800ms额外延迟
          setTimeout(() => {
            this.isGeneratingByAI = false;
            this.userInput = this.generatedDescription;
            this.$nextTick(this.resizeTextarea);
            this.showContentGeneratedEffect();
          }, extraDelay);
        }
      }, 200);

      // 超时保护：如果10秒还没生成完，就真的调用生成API
      setTimeout(() => {
        if (!this.generatedDescription) {
          clearInterval(checkInterval);
          console.log('⚠️ 静默生成超时，改为真实生成');
          this.generateAIDescription();
        }
      }, 10000);
    },

    generateAIDescription() {
      if (!this.sensorDataForAI || this.isGeneratingByAI) {
        return;
      }

      this.isGeneratingByAI = true;
      const AUTO_DESC_URL = 'https://api.withoutend.top/api/auto-desc';

      // 在描述请求中添加结构化提示
      const requestData = {
        sensorData: this.sensorDataForAI,
        structureHint: "请分析数据并生成一个问题描述，引导AI按照'异常描述'、'故障原因'、'解决方案'和'预防措施'四个部分回答"
      };

      request.post(AUTO_DESC_URL, requestData)
        .then(res => {
          console.log('--- 收到AI响应 ---', res);
          if (res && res.description) {
            const cleanedDescription = this.cleanThinkTags(res.description);
            this.generatedDescription = cleanedDescription;

            // 如果用户已经点击过魔法棒，立即显示
            if (this.hasClickedMagicWand) {
              this.userInput = cleanedDescription;
              this.$nextTick(this.resizeTextarea);
              this.showContentGeneratedEffect();
            }
          } else {
            this.$message.error('AI无法生成描述，请稍后重试。');
          }
        })
        .catch(error => {
          console.error('--- 调用AI服务出错 ---', error);
          this.$message.error('调用AI服务失败，请检查网络或联系管理员。');
        })
        .finally(() => {
          this.isGeneratingByAI = false;
        });
    },
    resizeTextarea() {
      const el = this.$refs.messageInput;
      if (el) {
        el.style.height = 'auto';
        el.style.height = (el.scrollHeight) + 'px';
      }
    },
    formatMessage(text) {
      if (!text) return '';
      const rawMarkup = marked(text, { gfm: true, breaks: true });
      return DOMPurify.sanitize(rawMarkup);
    },
    handleKeyDown(e) {
      if (e.key === 'Enter' && !e.shiftKey) {
        e.preventDefault();
        this.sendMessage();
      }
    },
    askSuggestedQuestion(question) {
      this.userInput = question;
      this.$refs.messageInput.focus();
      this.$nextTick(this.resizeTextarea);
    },
    sendMessage() {
      const message = this.userInput.trim();
      if (!message || this.isTyping) return;

      // 直接发送用户输入的消息，不添加任何额外内容
      this.sendMessageAction(message);
      this.userInput = '';
      this.$nextTick(() => {
         this.resizeTextarea();
         this.scrollToBottom();
      });
    },
    handleMessageAction(action, message) {
      if (action === 'copy') {
        navigator.clipboard.writeText(message.content);
        this.$message.success('已复制到剪贴板');
      } else if (action === 'work') {
          const { sensorId, latheName, axis } = this.$route.query || {};

          // 从AI回复中提取结构化字段
          const fields = this.extractFieldsFromResponse(message.content);

          // 构建设备信息字符串：设备名称+编号-传感器编号-传感器安装位置
          const deviceInfo = `${latheName || '未知设备'}-${sensorId || '未知传感器'}-${axis || '未知位置'}`;

          // 获取当前登录用户信息
          const currentUser = {
            id: this.$store.getters.id || this.$store.state.user.id,
            name: this.$store.getters.name || this.$store.state.user.name
          };

          console.log('🔍 当前用户信息:', currentUser);

          // 构建完整的查询参数，包含所有可能的字段
          const queryParams = {
            mode: 'create', // 确保以创建模式打开
            sensorId,
            latheName,
            axis,

            // 调试信息
            _debug_source: 'inquiry_page',

            // 用户信息
            reporterId: currentUser.id,
            reporter: currentUser.name,

            // 设备信息（按照数据表格式）
            deviceInfo: deviceInfo,

            // 故障等级和异常类型（AI应该输出数字）
            faultLevel: fields.faultLevel || '', // AI输出：0=紧急，1=重要，2=一般，3=轻微
            anomalyType: fields.anomalyType || '', // AI输出：0-9对应不同异常类型

            // 时间信息（使用本地时间）
            occurredTime: this.formatCurrentTime(),

            // 异常信息
            anomalyDescription: fields.anomalyDescription || message.content,
            affectedAxis: JSON.stringify(fields.affectedAxis || (axis ? [axis] : [])),

            // 故障分析信息
            faultCause: fields.faultCause || '',
            solution: fields.solution || '',
            troubleshootingProcess: fields.troubleshootingProcess || '',
            preventiveMeasures: fields.preventiveMeasures || '',
            similarCases: fields.similarCases || '',
            impactAssessment: fields.impactAssessment || '',

            // 其他可能的字段
            workSection: fields.workSection || '',
            productionPart: fields.productionPart || '',
            replacedParts: fields.replacedParts || '',
            toolsUsed: fields.toolsUsed || '',
            operationSteps: fields.operationSteps || ''
          };

          // 过滤掉空值，避免URL过长
          const filteredParams = {};
          Object.keys(queryParams).forEach(key => {
            const value = queryParams[key];
            if (value !== undefined && value !== null && value !== '') {
              filteredParams[key] = value;
            }
          });

          console.log('跳转到工单创建页面，参数:', filteredParams);
          console.log('📊 AI提取的字段:', fields);
          console.log('🎯 关键字段传递检查:', {
            故障等级: { AI提取: fields.faultLevel, 传递参数: queryParams.faultLevel },
            异常类型: { AI提取: fields.anomalyType, 传递参数: queryParams.anomalyType },
            轴向信息: { 原始axis: axis, AI提取: fields.affectedAxis, 传递参数: queryParams.affectedAxis },
            用户信息: { 用户ID: queryParams.reporterId, 用户名: queryParams.reporter }
          });

          this.$router.push({
            path: '/real/workorder',
            query: filteredParams
          });
        }
    },
    scrollToBottom() {
      this.$nextTick(() => {
        const el = this.$refs.chatHistory;
        if (el) el.scrollTop = el.scrollHeight;
      });
    },
    cleanThinkTags(text) {
      if (!text) return '';
      return text
        .replace(/<think>|<\/think>|【思考过程】|思考：|思考:|问题：|问题:|\[思考.*?\]|【思考.*?】/gi, '')
        .replace(/^\s*思考.*$/gmi, '')
        .trim();
    },




  }
};
</script>

<style scoped>
* {
    box-sizing: border-box;
    font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
}

.gelly-ai-page {
    display: flex;
    justify-content: center;
    align-items: center;
    height: calc(100vh - 84px);
    background: linear-gradient(135deg, #f5f7fa, #e4e7f5);
    padding: 24px;
}

.ai-container {
    width: 100%;
    height: 100%;
    background-color: #FFFFFF;
    border: 1px solid rgba(18, 17, 42, 0.07);
    border-radius: 28px;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    box-shadow: 0 30px 60px -20px rgba(92, 81, 233, 0.05);
}

.message-bubble-wrapper {
  display: flex;
  flex-direction: column;
  gap: 12px;
  width: 100%;
}

.thinking-process-container {
  width: 100%;
}

.thinking-collapse {
  border: none;
  background-color: transparent;
}
.thinking-collapse >>> .el-collapse-item__header {
  border: 1px solid #eef2f9;
  background-color: #fdfdff;
  border-radius: 12px;
  height: 44px;
  line-height: 44px;
  padding: 0 16px;
  font-size: 14px;
  color: #64748b;
  font-weight: 500;
  transition: all 0.2s ease;
}
.thinking-collapse >>> .el-collapse-item__header:hover {
  background-color: #f8faff;
  color: #5c51e9;
}
.thinking-collapse >>> .el-collapse-item__wrap {
  background-color: transparent;
  border: none;
  padding-top: 8px;
}
.thinking-collapse >>> .el-collapse-item__content {
  padding: 16px;
  font-size: 14px;
  color: #64748b;
  background: #fdfdff;
  border: 1px solid #eef2f9;
  border-radius: 12px;
  line-height: 1.7;
}

.thinking-panel {
  border: 1px solid #eef2f9;
  border-radius: 12px;
  background-color: #fdfdff;
  overflow: hidden;
}
.thinking-header {
  padding: 0 16px;
  height: 44px;
  line-height: 44px;
  font-size: 14px;
  color: #64748b;
  font-weight: 500;
  border-bottom: 1px solid #eef2f9;
}
.thinking-content {
  padding: 16px;
  font-size: 14px;
  line-height: 1.7;
  color: #64748b;
  word-break: break-word;
  white-space: pre-wrap;
}
.header-icon {
  color: #7e6cf7;
}

/* Header styling */
.app-header {
    padding: 18px 28px;
    border-bottom: 1px solid rgba(0, 0, 0, 0.05);
    display: flex;
    align-items: center;
    gap: 16px;
    flex-shrink: 0;
}

.back-btn {
    width: 40px;
    height: 40px;
    border-radius: 12px;
    background: #f8faff;
    border: 1px solid #e2e8f0;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    transition: all 0.2s;
    color: #64748b;
}
.back-btn:hover {
    background: #ffffff;
    transform: translateY(-1px);
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.ai-logo {
    width: 42px;
    height: 42px;
    background: linear-gradient(135deg, #5c51e9, #7e6cf7);
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 8px;
}
.header-logo-img {
    width: 100%;
    height: 100%;
}

.ai-title {
    font-size: 24px;
    font-weight: 600;
    color: #1e293b;
    letter-spacing: -0.5px;
}

/* Chat container */
.chat-history {
    flex: 1;
    padding: 32px;
    overflow-y: auto;
    display: flex;
    flex-direction: column;
    gap: 28px;
}
.chat-history::-webkit-scrollbar {
  width: 6px;
}
.chat-history::-webkit-scrollbar-track {
  background: #f1f1f1;
}
.chat-history::-webkit-scrollbar-thumb {
  background: #ccc;
  border-radius: 3px;
}
.chat-history::-webkit-scrollbar-thumb:hover {
  background: #bbb;
}

.message-row {
    display: flex;
    gap: 18px;
    max-width: 80%;
}

.message-row.ai {
    align-self: flex-start;
}

.message-row.user {
    align-self: flex-end;
    flex-direction: row-reverse;
}

.avatar-container {
    width: 42px;
    height: 42px;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
    overflow: hidden;
}
.avatar-img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.message-content {
    padding: 18px 22px;
    border-radius: 18px;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    gap: 12px;
    box-shadow: 0 4px 12px rgba(92, 81, 233, 0.04);
}

.ai .message-content {
    background: linear-gradient(to bottom right, #f8faff, #f1f5ff);
    border-bottom-left-radius: 4px;
}

.user .message-content {
    background: #FFFFFF;
    border: 1px solid #e2e8f0;
    border-bottom-right-radius: 4px;
}

.message-text {
    font-size: 15px;
    line-height: 1.7;
    color: #1e293b;
    white-space: pre-wrap;
    word-break: break-word;
}
.message-text >>> ul,
.message-text >>> ol {
  padding-left: 20px;
}
.message-text >>> li {
  margin-bottom: 8px;
}
.message-text >>> p {
  margin-bottom: 10px;
}
.message-text >>> p:last-child {
  margin-bottom: 0;
}

.message-details {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 4px;
}

.sender-name {
    font-weight: 600;
    font-size: 14px;
}

.ai .sender-name {
    color: #5c51e9;
}

.user .sender-name {
    color: #10b981;
}

.message-tools {
    display: flex;
    gap: 12px;
}

.tool-btn {
    display: flex;
    align-items: center;
    gap: 6px;
    padding: 6px 10px;
    background: rgba(255, 255, 255, 0.8);
    border: 1px solid #e2e8f0;
    border-radius: 8px;
    cursor: pointer;
    transition: all 0.25s;
    font-size: 13px;
    color: #64748b;
}

.tool-btn:hover {
    background: #ffffff;
    transform: translateY(-1px);
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

/* Loading state */
.loading-indicator {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    padding: 12px 20px;
    border-radius: 18px;
    background: linear-gradient(135deg, #f8faff, #f1f5ff);
}

.loading-dot {
    width: 10px;
    height: 10px;
    background: #5c51e9;
    border-radius: 50%;
    animation: bounce 1.4s infinite;
}

.loading-dot:nth-child(2) {
    animation-delay: 0.2s;
}

.loading-dot:nth-child(3) {
    animation-delay: 0.4s;
}

@keyframes bounce {
    0%, 100% { transform: translateY(-3px); opacity: 0.6; }
    50% { transform: translateY(3px); opacity: 1; }
}

/* Input area */
.input-container {
    padding: 24px 28px;
    border-top: 1px solid rgba(0, 0, 0, 0.05);
    background: #ffffff;
    flex-shrink: 0;
}

.input-box {
    position: relative;
    border-radius: 18px;
    overflow: hidden;
    border: 1px solid #dde2ea;
    transition: box-shadow 0.2s;
}
.input-box:focus-within {
    box-shadow: 0 0 0 3px rgba(92, 81, 233, 0.2);
    border-color: #7e6cf7;
}

.message-input {
    width: 100%;
    min-height: 56px;
    max-height: 200px;
    padding: 16px 80px 16px 20px;
    border: none;
    background: #ffffff;
    font-size: 15px;
    resize: none;
    outline: none;
    color: #1e293b;
    line-height: 1.6;
}

.message-input::placeholder {
    color: #94a3b8;
}

.input-controls {
    position: absolute;
    right: 8px;
    bottom: 8px;
    display: flex;
    gap: 8px; /* 添加固定间距 */
    align-items: center; /* 确保垂直居中对齐 */
}

.send-btn {
    width: 40px;
    height: 40px;
    border-radius: 12px;
    background: linear-gradient(135deg, #5c51e9, #7e6cf7);
    border: none;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    transition: all 0.3s;
}

.send-btn:hover {
    transform: scale(1.05);
    box-shadow: 0 4px 15px rgba(92, 81, 233, 0.25);
}
.send-btn:disabled {
    background: #c8d0e0;
    cursor: not-allowed;
}
.send-btn:disabled:hover {
    transform: none;
    box-shadow: none;
}

.ai-btn {
    position: relative; /* 改为相对定位 */
    right: auto; /* 移除绝对定位 */
    bottom: auto; /* 移除绝对定位 */
    width: 40px;
    height: 40px;
    border-radius: 12px;
    background: linear-gradient(135deg, #7e6cf7, #5c51e9);
    border: none;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    transition: all 0.3s;
    box-shadow: 0 2px 6px rgba(92, 81, 233, 0.2);
}
.ai-btn:hover {
  transform: scale(1.05);
  box-shadow: 0 4px 12px rgba(92, 81, 233, 0.3);
}
.ai-btn:disabled {
  background: #c8d0e0;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}
.ai-btn:disabled:hover {
  transform: none;
  box-shadow: none;
}
.ai-btn svg {
  filter: drop-shadow(0 1px 2px rgba(0, 0, 0, 0.1));
}
.ai-btn:disabled svg {
  opacity: 0.7;
}
.magic-wand-spin {
  display: inline-flex;
  align-items: center;
  animation: magic-spin 1.2s linear infinite;
}
@keyframes magic-spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}


/* Suggestions section */
.suggestions-container {
    padding: 0 28px 24px;
    display: flex;
    gap: 16px;
    flex-shrink: 0;
}

.suggestion-card {
    flex: 1;
    background: linear-gradient(135deg, #f8faff, #f1f5ff);
    border-radius: 14px;
    padding: 16px;
    cursor: pointer;
    transition: all 0.3s;
    border: 1px solid #eef2f9;
}

.suggestion-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 18px rgba(92, 81, 233, 0.08);
    border-color: #d1d8f7;
}

.suggestion-title {
    font-weight: 600;
    font-size: 15px;
    color: #5c51e9;
    margin-bottom: 8px;
}

.suggestion-text {
    font-size: 14px;
    color: #64748b;
    line-height: 1.5;
}
</style>
